package com.ycl.gatewayservice.filter;


import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-1)
public class MyGlobalExceptionHandler implements ErrorWebExceptionHandler {

    //日志输出对象
    private static Logger logger = LoggerFactory.getLogger(MyGlobalExceptionHandler.class);

    /**
     * 异常处理
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        //判断响应是否提交，如果提交了，就直接报错
        if(response.isCommitted()){
            return Mono.error(ex);
        }
        //如果没有提交，则判断异常的类型
        String msg = "";
        if(ex instanceof NotFoundException){
            msg = "你的服务跑不见了:)";
        }else if(ex instanceof ResponseStatusException){
            msg = "你的响应出现问题：" + ex.getMessage();
        }else{
            msg = "你的服务器出现了问题^_^";
        }
        logger.debug("服务器异常处理：{}",msg);
        //将数据返回给客户端
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(msg).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
